<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="视频ID" prop="videoId">
        <el-input v-model="queryParams.videoId" placeholder="请输入视频ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户ID" prop="createUserId">
        <el-input v-model="queryParams.createUserId" placeholder="请输入用户ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="视频标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入视频标题" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable size="small" style="width: 240px">
          <el-option v-for="item in auditStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="showFlag" type="card" @tab-click="showFlagSwitch">
      <el-tab-pane label="已发布" name="send" />
      <el-tab-pane label="待发布" name="unSend" />
    </el-tabs>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">发布视频
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频ID" align="center" prop="videoId" />
      <el-table-column label="用户ID" align="center" prop="createUserId" />
      <el-table-column label="视频标题" align="center" prop="title" />
      <el-table-column label="视频封面" align="center" prop="txVideoImage">
        <template slot-scope="scope">
          <el-image :src="requestUrl + scope.row.txVideoImage" style="
              width: 140px;
              height: 100px;
              float: left;
              display: inline-block;
            " />
        </template>
      </el-table-column>
      <el-table-column label="视频详情" align="center" prop="">
        <template slot-scope="scope">
          <a :href="scope.row.txVideo" target="_blank" style="color: #337ab7" v-if="scope.row.txVideo">
            查看视频
          </a>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createDate" />
      <el-table-column label="发布时间" align="center" prop="releaseTime" />
      <el-table-column label="下架时间" align="center" prop="unReleaseTime" />
      <el-table-column label="推荐" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.recommendFlag" :active-value="1" :inactive-value="0"
            @change="recommendChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="showFlag">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.showFlag == 0">待发布</el-tag>
          <el-tag type="success" v-if="scope.row.showFlag == 1">已发布</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.auditStatus == -1">审核拒绝</el-tag>
          <el-tag v-if="scope.row.auditStatus == 0">待审核</el-tag>
          <el-tag type="success" v-if="scope.row.auditStatus == 1">审核通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-check" v-if="scope.row.auditStatus == 0"
            @click="handleAudit(scope.row, 1)">通过
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-close" v-if="scope.row.auditStatus == 0"
            @click="handleAudit(scope.row, -1)">拒绝
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-top"
            v-if="scope.row.auditStatus == 1 && scope.row.showFlag == 0 && scope.row.releaseTime == null"
            @click="handleRelease(scope.row)">发布
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-bottom"
            v-if="scope.row.auditStatus == 1 && scope.row.showFlag == 1" @click="handleUnRelease(scope.row)">下架
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!--  新增视频  -->
    <el-dialog :title="title" :visible.sync="addVideoFormDisable" width="800px" append-to-body @close="cancel">
      <el-form ref="formRef" :model="form" label-width="150px" :rules="rules">
        <el-form-item label="视频发布人" prop="createUserId">
          <el-select v-model="form.createUserId" placeholder="请选择">
            <el-option v-for="item in videoUserList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频标题:" prop="title">
          <el-input v-model="form.title" maxlength="20" show-word-limit placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述:" prop="notes">
          <el-input v-model="form.notes" maxlength="60" show-word-limit type="textarea" :rows="3" placeholder="请输入视频描述" />
        </el-form-item>
        <el-form-item label="视频封面:" prop="txVideoImage">
          <imageUpload :limit="1" :file-size="3" v-model="form.txVideoImage" />
        </el-form-item>
        <el-form-item label="视频:" prop="txVideo">
          <CTTupload :limit="1" action="#" v-model="form.txVideo" ref="cttUpload" :on-success="uploadVideoSuccess"
            :on-remove="handleRemoveVideo" :http-request="uploadHttpRequest" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4文件，且视频不超过100mb
            </div>
          </CTTupload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="releaseFormDisable" width="850px" append-to-body>
      <el-form ref="releaseForm" :model="releaseForm" label-width="100px">
        <el-form-item label="发布设置">
          <el-radio-group v-model="releaseType">
            <el-radio label="1">立即发布</el-radio>
            <el-radio label="2">自定义发布时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-if="releaseType == '2'" v-model="releaseForm.releaseTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架设置">
          <el-radio-group v-model="unReleaseType">
            <el-radio label="1">永久不下架</el-radio>
            <el-radio label="2">自定义下架时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-if="unReleaseType == '2'" v-model="releaseForm.unReleaseTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择下架时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="submitReleaseForm">确 认</el-button>
        <el-button @click="cancelReleaseForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listVideo,
  delVideo,
  updateShowFlag,
  videoSignature,
  saveVideo,
  uploads,
  auditVideo,
  unRelease,
  release,
  recommend,
  videolistUser,
} from "@/api/admin/video";
import CTTupload from "@/components/upload/index.vue";
import TcVod from "vod-js-sdk-v6";
import { base64ConvertFile, getVideoBase64 } from "@/utils/index";
import { getToken } from "@/utils/auth";

export default {
  components: { CTTupload },
  name: "Video",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频管理表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        title: '',
        showFlag: 1,
        auditStatus: null
      },
      dateRange: [],
      form: {},
      addVideoFormDisable: false,
      rules: {
        createUserId: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
        title: [{ required: true, message: "请输入视频标题", trigger: "blur" }],
        notes: [{ required: true, message: "请输入视频描述", trigger: "blur" }],
        txVideoImage: [{ required: true, message: '请选择图片', trigger: ['blur', 'change'] }]
      },
      statusOptions: [
        {
          value: "0",
          label: "隐藏",
        },
        {
          value: "1",
          label: "显示",
        },
      ],
      auditStatusOptions: [
        {
          value: "-1",
          label: "审核拒绝",
        },
        {
          value: "0",
          label: "待审核",
        },
        {
          value: "1",
          label: "审核通过",
        }
      ],
      showFlag: "send",
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/upload/uploadImg/3",
      },
      videoUserList: [],
      releaseFormDisable: false,
      releaseForm: {},
      releaseType: '1',
      unReleaseType: '1',
      requestUrl: this.$img.requestUrl,
    };
  },
  created () {
    this.getList();
  },
  methods: {
    //修改视频推荐
    recommendChange (row) {
      let text = row.recommendFlag === 0 ? "停用" : "启用";
      this.$confirm('确认要"' + text + '""' + "该视频的推荐吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return recommend({
            videoId: row.videoId,
            recommendFlag: row.recommendFlag,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.recommendFlag = row.recommendFlag == "0" ? 1 : 0;
        });
    },
    //获取发布人列表
    getVideoUser () {
      return videolistUser().then((res) => {
        return res;
      });
    },
    /** 查询视频管理列表 */
    getList () {
      this.loading = true;
      listVideo(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.videoList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.videoId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.videoId || this.ids;
      this.$confirm('是否确认删除表编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delVideo(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    // 表单重置
    reset () {
      try {
        this.$refs.cttUpload.handleRemove();
      } catch (err) {
        console.log(err, "err");
      }
      this.resetForm("formRef");
    },
    // 用户状态修改
    handleStatusChange (row) {
      let text = row.showFlag === "0" ? "显示" : "隐藏";
      this.$confirm("确认要" + text + "该视频吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return updateShowFlag(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.showFlag = row.showFlag === "0" ? "1" : "0";
        });
    },
    //新增视频
    async handleAdd () {
      this.videoUserList = [];
      this.title = "发布视频";
      this.addVideoFormDisable = true;
      let response = await this.getVideoUser();
      this.videoUserList = response.data;
      console.log(this.videoUserList);
    },
    // 视频上传成功处理
    uploadVideoSuccess (response) {
      this.upload.isUploading = false;
      this.form.txVideo = response.data.list[0].filePath;
      this.form.videoCapture = response.data.list[0].cover;
      this.form.txVideoId = response.data.list[0].fileId;
      this.msgSuccess(response.msg);
    },
    handleRemoveVideo () {
      this.form.txVideo = null;
    },
    //获取视频签名
    getVideoSignature () {
      return videoSignature().then((res) => {
        return res.data;
      });
    },
    //视频上传请求
    uploadHttpRequest (file) {
      const _this = this;
      //必须以函数的形式返回 sdk参数限制
      // 获取视频签名
      const getSignature = async function () {
        return await _this.getVideoSignature();
      };
      // 前文中所述的获取上传签名的函数
      const tcVod = new TcVod({
        getSignature: getSignature,
      });
      const uploader = tcVod.upload({
        mediaFile: file.file, // 这里腾讯云需要获取到file文件里的name，根据你file结构进行填写
      });
      //this.uploaderG = uploader // 定义全局用于取消上传
      // 进度
      uploader.on("media_progress", function (info) {
        //调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
        file.onProgress({ percent: info.percent * 100 });
      });
      // 上传成功
      uploader
        .done()
        .then((doneResult) => {
          getVideoBase64(file.file)
            .then((Result) => {
              let Ifile = base64ConvertFile(Result);
              let formData = new FormData();
              formData.append("file", Ifile, Ifile.name);
              uploads(formData, file)
                .then((response) => {
                  let data = {
                    code: 200,
                    msg: "上传成功",
                    data: {
                      list: [
                        {
                          filePath: doneResult.video.url,
                          cover: response.data.list[0].filePath,
                          fileId: doneResult.fileId,
                        },
                      ],
                    },
                  };
                  file.onSuccess(data);
                })
                .catch((err) => {
                  console.log(err);
                  this.msgError(err);
                });
            })
            .catch((err) => {
              this.msgError("上传失败");
            });
        })
        .catch((err) => {
          this.msgError("上传失败");
        });
    },
    //提交按钮
    submitForm () {
      this.$refs["formRef"].validate((valid) => {
        if (!this.form.txVideo) {
          this.$message.warning("请先上传视频");
          return;
        }
        if (valid) {
          saveVideo(this.form).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("新增视频成功!");
              this.addVideoFormDisable = false;
              this.getList();
              this.reset();
              try {
                this.$refs.cttUpload.handleRemove();
              } catch (err) {
                console.log(err, "err");
              }
            }
          });
        }
      });
    },
    cancel () {
      this.reset();
      this.addVideoFormDisable = false;
    },
    handleAudit (row, auditStatus) {
      let auditForm = { videoId: row.videoId, auditStatus: auditStatus }
      let title = '';
      if (auditStatus == 1) {
        title = "通过";
      } else if (auditStatus == -1) {
        title = "拒绝";
      }
      this.$confirm('是否确认' + title + '该视频?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return auditVideo(auditForm);
      }).then(() => {
        this.getList();
        this.msgSuccess(title + "成功！");
      }).catch(function () {
      });
    },
    showFlagSwitch (tab) {
      const showFlagName = tab.name;
      let showFlag = 1;
      if (showFlagName === "unSend") {
        showFlag = 0;
      } else if (showFlagName === "send") {
        showFlag = 1;
      }
      this.queryParams.showFlag = showFlag;
      this.getList();
    },
    //视频审核通过
    handleRelease (row) {
      this.releaseFormDisable = true;
      this.title = "发布设置";
      this.releaseForm.videoId = row.videoId;
    },
    handleUnRelease (row) {
      this.$confirm("确认下架该视频?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return unRelease(row.videoId)
      }).then(() => {
        this.getList();
        this.msgSuccess("视频下架成功!");
      }).catch(function () {
      });
    },
    //提交按钮
    submitReleaseForm () {
      this.$refs["releaseForm"].validate((valid) => {
        if (valid) {
          this.releaseForm.releaseType = this.releaseType;
          this.releaseForm.unReleaseType = this.unReleaseType;
          console.log(this.releaseForm);
          release(this.releaseForm).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("视频发布成功!");
              this.releaseFormDisable = false;
              this.getList();
              this.resetReleaseForm();
            }
          });
        }
      });
    },
    cancelReleaseForm () {
      this.resetReleaseForm();
      this.releaseFormDisable = false;
    },
    resetReleaseForm () {
      this.releaseForm = {};
      this.releaseType = '1';
      this.unReleaseType = '1';
      this.resetForm("releaseForm");
    },
  },
};
</script>
